<template>
<div>
    <header class="header">
        <div class="header-content">
            <div class="header-title">消息</div>
            <div class="header-actions">
                <a href="#" class="action-btn add-btn">
                    <i class="icon-add"></i>
                </a>
            </div>
        </div>
    </header>

    <main class="main-content">
        <!-- 功能分类区域 -->
        <div class="feature-categories">
            <div class="category-item" @click="navigateToComments">
                <div class="category-icon comment-icon">
                    <svg style="transform: translateY(3px);" t="1758987497698" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="17577" width="28" height="28">
                        <path d="M277.333333 85.333333C148.240597 85.333333 42.666667 187.758635 42.666667 312.888875L42.666667 464.592597C42.666667 589.72288 148.240597 692.148139 277.333333 692.148139L316.444459 692.148139 316.444459 919.703723 584.616277 692.148139 746.666667 692.148139C875.733333 692.148139 981.333333 589.72288 981.333333 464.592597L981.333333 312.888875C981.333333 187.733333 875.733333 85.333333 746.666667 85.333333L277.333333 85.333333Z" 
                            fill="#8feabd" p-id="17578">
                        </path>
                    </svg>
                </div>
                <div class="category-name">我的回复</div>
            </div>
            <div class="category-item" @click="navigateToLikes">
                <div class="category-icon like-icon">
                    <svg t="1758986638783" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="6568" width="33" height="33">
                        <path d="M795.7504 444.416H614.7072c70.144-259.072-48.3328-272.384-48.3328-272.384-50.176 0-39.8336 39.7312-43.6224 46.2848C522.752 345.088 388.1984 444.416 388.1984 444.416v359.3216c0 35.4304 48.3328 48.2304 67.2768 48.2304h272.0768c25.6 0 46.4896-67.1744 46.4896-67.1744 67.2768-228.864 67.2768-296.96 67.2768-296.96 0-47.2064-45.568-43.4176-45.568-43.4176z m0 0M313.856 444.5184H205.4144c-22.4256 0-22.7328 22.016-22.7328 22.016l22.4256 362.3936c0 23.04 23.1424 23.04 23.1424 23.04h93.7984c19.5584 0 19.3536-15.2576 19.3536-15.2576V471.9616c0-27.8528-27.5456-27.4432-27.5456-27.4432z m0 0" 
                            p-id="6569" fill="#f3a9aa">
                        </path>
                    </svg>
                </div>
                <div class="category-name">我的获赞</div>
            </div>
            <div class="category-item" @click="navigateToFans">
                <div class="category-icon follow-icon">
                    <svg t="1758988258609" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="26494" width="30" height="30">
                        <path d="M861.090909 786.385455a158.487273 158.487273 0 0 1-33.978182 101.934545A102.4 102.4 0 0 1 744.727273 930.909091H279.272727a102.167273 102.167273 0 0 1-82.152727-42.589091A158.952727 158.952727 0 0 1 162.909091 786.385455 744.727273 744.727273 0 0 1 167.563636 698.181818a467.083636 467.083636 0 0 1 17.221819-83.083636 279.272727 279.272727 0 0 1 31.883636-70.516364 150.807273 150.807273 0 0 1 51.2-48.64 144.523636 144.523636 0 0 1 73.541818-18.850909 235.752727 235.752727 0 0 0 170.589091 69.818182 235.752727 235.752727 0 0 0 170.821818-69.818182 142.429091 142.429091 0 0 1 73.541818 18.850909 153.134545 153.134545 0 0 1 51.2 48.64 279.272727 279.272727 0 0 1 31.883637 71.214546 462.894545 462.894545 0 0 1 17.221818 82.385454 800.116364 800.116364 0 0 1 4.421818 88.203637zM660.014545 154.530909A201.774545 201.774545 0 0 1 721.454545 302.545455a201.774545 201.774545 0 0 1-61.44 148.014545A201.774545 201.774545 0 0 1 512 512a201.774545 201.774545 0 0 1-148.014545-61.44A201.774545 201.774545 0 0 1 302.545455 302.545455a201.774545 201.774545 0 0 1 61.44-148.014546A201.774545 201.774545 0 0 1 512 93.090909a201.774545 201.774545 0 0 1 148.014545 61.44z" 
                            p-id="26495" fill="#94c1ea">
                        </path>
                    </svg>
                </div>
                <div class="category-name">新增粉丝</div>
            </div>
            
        </div>
        
        <!-- 消息列表 -->
        <div class="message-section">

            <div v-for="item in conversationList" :key="item.id" class="message-item" 
                 @click="navigateToChat(item.talkerId)"
                 @contextmenu.prevent="showContextMenu($event, item)"
                 @touchstart="handleTouchStart($event, item)"
                 @touchend="handleTouchEnd"
                 @touchmove="handleTouchMove">
                <!-- 头像 -->
                <div class="avatar user-avatar">
                    <img v-if="item.avatar" :src="item.avatar" alt="" class="avatar-img" />
                    <div v-else class="avatar-replace" style="background: #ff6b6b;">{{ item.name?.charAt(0) }}</div>
                </div>

                <!-- 最新消息  -->
                <div class="message-content">
                    <div class="message-header">
                        <div class="sender-name">{{ item.name }}</div>
                        <div class="message-time">{{ formatTime(item.lastMessageTime) }}</div>
                    </div>
                    <div v-if="item.lastMessageIsRevoked" class="message-preview">
                        <span>{{ item.lastMessageSenderId !== user_Store.userInfo.id ? '对方' : '你'}}撤回了一条消息&ensp;</span>
                    </div>
                    <div v-else class="message-preview">{{ item.lastMessageContent }}</div>
                </div>

                <!-- 未读标识 unreadMessageCount -->
                <div v-if="item.unreadMessageCount > 0" class="unread-badge">
                    {{ item.unreadMessageCount > 99 ? '99+' : item.unreadMessageCount }}
                </div>
            </div>

            <!-- 活动消息 -->
            <div class="message-item">
                <div class="avatar activity-avatar">
                    <i class="icon-activity"></i>
                </div>
                <div class="message-content">
                    <div class="message-header">
                        <div class="sender-name">活动消息</div>
                        <div class="message-time">09-04</div>
                    </div>
                    <div class="message-preview">可算找到你了！参加创作激励计划...</div>
                </div>
                <div class="unread-badge">99+</div>
            </div>
            
            <!-- 系统消息 -->
            <div class="message-item">
                <div class="avatar system-avatar">
                    <i class="icon-notification"></i>
                </div>
                <div class="message-content">
                    <div class="message-header">
                        <div class="sender-name">系统消息</div>
                        <div class="message-time">2024-06-24</div>
                    </div>
                    <div class="message-preview">欢迎新朋友~</div>
                </div>
            </div>
        </div>
        
        <!-- 可能感兴趣的人 -->
        <div class="interest-section">
            <div class="interest-header">
                <span>你可能感兴趣的人</span>
                <a href="#" class="close-btn">关闭</a>
            </div>
            
            <div class="interest-list">
                <!-- 推荐用户1 -->
                <div class="interest-item">
                    <div class="user-avatar">
                        <img src="" alt="" class="avatar-img" />
                    </div>
                    <div class="user-info">
                        <div class="user-name">指是弹琴</div>
                        <div class="user-desc">音乐内容热门作者</div>
                    </div>
                    <button class="follow-btn">关注</button>
                    <a href="#" class="dismiss-btn">×</a>
                </div>
                
                <!-- 推荐用户2 -->
                <div class="interest-item">
                    <div class="user-avatar">
                        <img src="" alt="" class="avatar-img" />
                    </div>
                    <div class="user-info">
                        <div class="user-name">吾空空</div>
                        <div class="user-desc">城市出行内容热门作者</div>
                    </div>
                    <button class="follow-btn">关注</button>
                    <a href="#" class="dismiss-btn">×</a>
                </div>
                
                <!-- 推荐用户3 -->
                <div class="interest-item">
                    <div class="user-avatar">
                        <img src="" alt="" class="avatar-img" />
                    </div>
                    <div class="user-info">
                        <div class="user-name">豆豆本豆</div>
                        <div class="user-desc">时尚内容热门作者</div>
                    </div>
                    <button class="follow-btn">关注</button>
                    <a href="#" class="dismiss-btn">×</a>
                </div>
                
                <!-- 推荐用户4 -->
                <div class="interest-item">
                    <div class="user-avatar">
                        <img src="" alt="" class="avatar-img" />
                    </div>
                    <div class="user-info">
                        <div class="user-name">😎NPC_Ou</div>
                        <div class="user-desc">1个共同联系人</div>
                    </div>
                    <button class="follow-btn">关注</button>
                    <a href="#" class="dismiss-btn">×</a>
                </div>
            </div>
        </div>
    </main>

    <!-- 底部占位盒子 -->
    <div style="height: 70px;"></div>

    <!-- 右键菜单 -->
    <div v-if="contextMenuVisible" class="context-menu" :style="{ top: contextMenuPosition.y + 'px', left: contextMenuPosition.x + 'px' }">
        <div class="menu-item" @click="confirmDeleteConversation">删除会话</div>
    </div>

    <!-- 长按菜单 -->
    <div v-if="longPressMenuVisible" class="long-press-menu" :style="{ top: longPressMenuPosition.y + 'px', left: longPressMenuPosition.x + 'px' }">
        <div class="menu-item" @click="confirmDeleteConversation">删除会话</div>
    </div>

    <!-- 确认对话框 -->
    <div v-if="confirmDialogVisible" class="confirm-dialog-overlay" @click="closeConfirmDialog">
        <div class="confirm-dialog" @click.stop>
            <div class="dialog-title">确认删除</div>
            <div class="dialog-content">确认删除该会话吗？聊天记录将被清理。</div>
            <div class="dialog-actions">
                <button class="btn-cancel" @click="closeConfirmDialog">取消</button>
                <button class="btn-confirm" @click="deleteConversation">删除</button>
            </div>
        </div>
    </div>
</div>
</template>

<script lang="ts" setup>
import { ref,onMounted } from 'vue'
import { useRouter } from 'vue-router'
import api from '@/api/index.js'
import { formatTime } from '@/utils/format.js'
import { UserInfoStore } from '@/stores/userInfoStore'
import { ConversationStore } from '@/stores/conversationStore'
import { ChatUserInfoStore } from '@/stores/chatUserInfoStore'
import { TipStore } from '@/stores/tipStore'

const router = useRouter()
const user_Store = UserInfoStore()
const conversation_Store = ConversationStore()
const chatUserInfo_Store = ChatUserInfoStore()
const tip_Store = TipStore()

// 基础数据
const conversationList = ref([]) // 会话列表（用户之间的聊天）
const selectedConversation = ref(null)
const confirmDialogVisible = ref(false)

// 检测是否为移动设备
const isMobile = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
}

// #region ==================== PC端功能 ====================
// 右键菜单相关
const contextMenuVisible = ref(false)
const contextMenuPosition = ref({ x: 0, y: 0 })

// 显示右键菜单
const showContextMenu = (event, conversation) => {
    if (isMobile()) return // 移动设备不显示右键菜单
    
    selectedConversation.value = conversation
    contextMenuPosition.value = {
        x: event.clientX,
        y: event.clientY
    }
    contextMenuVisible.value = true
    
    // 点击其他地方关闭菜单
    document.addEventListener('click', hideContextMenu)
}

// 隐藏右键菜单
const hideContextMenu = () => {
    contextMenuVisible.value = false
    document.removeEventListener('click', hideContextMenu)
}
// #endregion


// #region ==================== 移动端功能 ====================
// 长按菜单相关
const longPressMenuVisible = ref(false)
const longPressMenuPosition = ref({ x: 0, y: 0 })
const longPressTimer = ref(null)
const touchStartTime = ref(0)
const isTouchMoved = ref(false)

// 处理触摸开始事件
const handleTouchStart = (event, conversation) => {
    if (!isMobile()) return // 非移动设备不处理长按
    
    touchStartTime.value = Date.now()
    isTouchMoved.value = false
    selectedConversation.value = conversation
    
    // 设置长按定时器
    longPressTimer.value = setTimeout(() => {
        if (!isTouchMoved.value) {
            // 计算菜单位置
            const touch = event.touches[0]
            longPressMenuPosition.value = {
                x: touch.clientX,
                y: touch.clientY
            }
            longPressMenuVisible.value = true
        }
    }, 500) // 长按500毫秒触发
}

// 处理触摸移动事件
const handleTouchMove = () => {
    if (!isMobile()) return // 非移动设备不处理长按
    
    isTouchMoved.value = true
    if (longPressMenuVisible.value) {
        longPressMenuVisible.value = false // 如果在触摸的时候移动则不显示菜单
    }
}

// 处理触摸结束事件
const handleTouchEnd = () => {
    if (!isMobile()) return // 非移动设备不处理长按
    
    clearTimeout(longPressTimer.value)
    
    // 如果不是长按状态，则正常跳转到聊天页面
    if (!longPressMenuVisible.value && !isTouchMoved.value && Date.now() - touchStartTime.value < 500) {
        // 这里可以添加点击跳转的逻辑，但已经在@click中处理了
    }
}
// #endregion


// #region ==================== 通用功能 ====================
// 显示确认删除对话框
const confirmDeleteConversation = () => {
    contextMenuVisible.value = false
    longPressMenuVisible.value = false
    confirmDialogVisible.value = true
}

// 关闭确认对话框
const closeConfirmDialog = () => {
    confirmDialogVisible.value = false
}

// 跳转到评论和@页面
function navigateToComments() {
  router.push({
    name: 'CommentReplies'
  })
}

// 跳转到赞和收藏页面
function navigateToLikes() {
  // 跳转到赞和收藏页面
  router.push({
    name: 'LikesReceived'
  })
}

// 跳转到粉丝列表页面
function navigateToFans() {
  router.push({
    name: 'FollowList',
    query: { type: 'followers' }
  })
}

// 跳转到聊天界面（目前只支持跳转私聊）
function navigateToChat(talkerId) {
    let conversation:any = conversationList.value.find(c => c.talkerId === talkerId)
    conversation_Store.conversationInfo = conversation
    router.push({
        path: '/chat',
        query: { 
            talkerId, 
        }
    })
}
// #endregion


// #region ==================== 前后端交互 ====================
// 删除会话
const deleteConversation = async () => {
    if (!selectedConversation.value) return
    
    try {
        const res = await api.Sessions_Delete(selectedConversation.value.id)
        if (res.data.code == 1) {
            const index = conversationList.value.findIndex(item => item.id === selectedConversation.value.id)
            if (index !== -1) {
                conversationList.value.splice(index, 1) // 删除成功，从列表中移除
            }
        } else {
            tip_Store.errorTip('删除会话失败')
            console.error('删除会话失败:', res.data.message)
        }
    } catch (error) {
        console.error('删除会话出错:', error)
    } finally {
        closeConfirmDialog()
    }
}

// 获取用户会话列表
const getSessions = async() => { 
    // 1. 获取会话列表
    let res_session = await api.Sessions_GetByUserId()
    if (res_session.data.code != 1) return
    const sessions_temp = res_session?.data?.data ?? []
    if(sessions_temp.length == 0) return

    // 2. 收集所有有效的 talkerId
    const talkerIdSet = new Set(
      sessions_temp
        .filter(s => Boolean(s.talkerId))
        .map(s => s.talkerId)
    );
    const talkerIdList = Array.from(talkerIdSet);

    // 3.获取用户信息，并设置字段（如果有就拿缓存的，没有就请求后端）
    let user_list = []
    if(chatUserInfo_Store.chatUserList.length != 0){
        talkerIdList.forEach(id => {
            let existingUser = chatUserInfo_Store.getUserById(id);
            if (existingUser) {
                user_list.push(existingUser);
            }
        });
    }else{
        let res_user = await api.User_GetById_ConvListQuery(talkerIdList)
        user_list = res_user.data.data
        user_list.forEach(u => {
            chatUserInfo_Store.addOrUpdateUser(u)
        })
    }
    const userMap = new Map(user_list.map(user => [user.id, user])); // 将用户列表转换为 Map 以便高效查找
    
    conversationList.value = sessions_temp.map(session => {
        const talker:any = userMap.get(session.talkerId);
        if (talker) {
            return {
                ...session,
                name: talker.username, // 会话名称
                avatar: talker.avatarUrl, // 头像地址
            };
        }
        return session;
    });
}
// #endregion


onMounted(async()=>{
    await getSessions() // 获取用户会话列表
})

</script>

<style lang="scss" scoped>
/* #region 头部 */
.header {
    background: white;
    padding: 15px 20px;
    box-shadow: 0 1px 5px rgba(0,0,0,0.05);
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 100;
}

.header-content {
    display: flex;
    justify-content: space-between;
    align-items: center;
    max-width: 800px;
    margin: 0 auto;
}

.header-title {
    font-size: 18px;
    font-weight: 500;
    color: #333;
}

.header-actions {
    display: flex;
    gap: 15px;
}

.action-btn {
    font-size: 22px;
    cursor: pointer;
    text-decoration: none;
    color: #333;
    display: flex;
    align-items: center;
    justify-content: center;
}

.icon-add:before {
    content: "+";
    font-weight: 300;
}
/* #endregion 头部结束 */


/* #region 内容 */
.main-content {
    margin-top: 60px;
    margin-left: auto;
    margin-right: auto;
    background: #f8f8f8;
    min-height: calc(100vh - 130px);
}

/* 功能分类区域 */
.feature-categories {
    display: flex;
    justify-content: space-around;
    padding: 20px 10px;
    background: white;
    margin-bottom: 10px;
}

.category-item {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 33.33%;
    cursor: pointer;
    transition: all 0.2s ease-in-out;
}

.category-item:hover {
    opacity: 0.8;
}

.category-icon {
    width: 50px;
    height: 50px;
    border-radius: 15px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 8px;
}

.like-icon {
    background: #ffecec;
    color: #ff6b6b;
}

.follow-icon {
    background: #e6f3ff;
    color: #1890ff;
}

.comment-icon {
    background: #e8f8f0;
    color: #4cd964;
}

.category-name {
    font-size: 14px;
    color: #333;
}

/* 消息列表 */
.message-section {
    background: white;
    margin-bottom: 10px;
}

.message-item {
    display: flex;
    align-items: center;
    padding: 15px 20px;
    border-bottom: 1px solid #f5f5f5;
    position: relative;
    cursor: pointer;
}

.message-item:last-child {
    border-bottom: none;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    overflow: hidden;
}

.activity-avatar {
    background: #4a90e2;
    color: white;
}

.system-avatar {
    background: #ff9500;
    color: white;
}

.user-avatar {
    background: #f5f5f5;
}

.avatar-img {
    width: 100%;
    height: 100%;
    object-fit: cover;
}

.avatar-replace{
    width: 100%;
    height: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 16px;
}

.message-content {
    flex: 1;
    min-width: 0;
}

.message-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 5px;
}

.sender-name {
    font-weight: 500;
    font-size: 16px;
    color: #333;
}

.message-time {
    font-size: 12px;
    color: #999;
}

.message-preview {
    color: #666;
    font-size: 14px;
    line-height: 1.4;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    margin-right: 35px;
}

.unread-badge {
    min-width: 18px;
    height: 18px;
    background: #ff3b30;
    color: white;
    border-radius: 10px;
    padding: 2px 6px;
    font-size: 11px;
    font-weight: 500;
    position: absolute;
    right: 20px;
    top: 65%;
    transform: translateY(-50%);
    display: flex;
    align-items: center;
    justify-content: center;
}

/* 可能感兴趣的人 */
.interest-section {
    background: white;
    padding: 15px 0;
}

.interest-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 0 15px 15px;
    border-bottom: 1px solid #f5f5f5;
    font-size: 15px;
    color: #333;
}

.close-btn {
    color: #999;
    font-size: 14px;
    text-decoration: none;
}

.interest-list {
    padding: 0 15px;
}

.interest-item {
    display: flex;
    align-items: center;
    padding: 15px 0;
    border-bottom: 1px solid #f5f5f5;
    position: relative;
}

.interest-item:last-child {
    border-bottom: none;
}

.user-avatar {
    width: 40px;
    height: 40px;
    border-radius: 50%;
    overflow: hidden;
    margin-right: 12px;
    background: #f5f5f5;
}

.user-info {
    flex: 1;
    min-width: 0;
}

.user-name {
    font-size: 15px;
    font-weight: 500;
    color: #333;
    margin-bottom: 3px;
}

.user-desc {
    font-size: 12px;
    color: #999;
}

.follow-btn {
    padding: 5px 15px;
    border-radius: 15px;
    background: #fff;
    color: #ff6b6b;
    border: 1px solid #ff6b6b;
    font-size: 14px;
    cursor: pointer;
    margin-right: 10px;
}

.dismiss-btn {
    color: #ccc;
    font-size: 18px;
    text-decoration: none;
    display: flex;
    align-items: center;
    justify-content: center;
}
/* #endregion 内容结束 */

/* #region pc右键菜单 和 移动端长按菜单 */
.context-menu, .long-press-menu {
    position: fixed;
    background: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
    z-index: 1000;
    min-width: 120px;
    overflow: hidden;
}

.menu-item {
    padding: 12px 16px;
    font-size: 14px;
    color: #333;
    cursor: pointer;
    transition: background-color 0.2s;
}

.menu-item:hover {
    background-color: #f5f5f5;
}

.menu-item:active {
    background-color: #e8e8e8;
}

/* #endregion 右键菜单和长按菜单结束 */

/* #region 确认对话框 */
.confirm-dialog-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 2000;
}

.confirm-dialog {
    background: white;
    border-radius: 12px;
    width: 80%;
    max-width: 300px;
    overflow: hidden;
    animation: dialog-fade-in 0.3s ease-out;
}

@keyframes dialog-fade-in {
    from {
        opacity: 0;
        transform: scale(0.9);
    }
    to {
        opacity: 1;
        transform: scale(1);
    }
}

.dialog-title {
    padding: 20px 20px 10px;
    font-size: 18px;
    font-weight: 500;
    color: #333;
    text-align: center;
}

.dialog-content {
    padding: 0 20px 20px;
    font-size: 14px;
    color: #666;
    text-align: center;
    line-height: 1.5;
}

.dialog-actions {
    display: flex;
    border-top: 1px solid #eee;
}

.btn-cancel, .btn-confirm {
    flex: 1;
    padding: 12px 0;
    font-size: 16px;
    border: none;
    background: none;
    cursor: pointer;
    transition: background-color 0.2s;
}

.btn-cancel {
    color: #666;
    border-right: 1px solid #eee;
}

.btn-cancel:hover {
    background-color: #f5f5f5;
}

.btn-confirm {
    color: #ff3b30;
}

.btn-confirm:hover {
    background-color: #fff5f5;
}

/* #endregion 确认对话框结束 */
</style>